<template>
  <div class="vacation-rules-container">
    <div class="page-header">
      <el-button type="primary" @click="handleAdd">
        <el-icon>
          <Plus />
        </el-icon>
        新增考勤组
      </el-button>
    </div>

    <el-table v-loading="loading" :data="dataList" border style="width: 100%">
      <el-table-column prop="name" label="名称" min-width="120" />
      <el-table-column label="类型" min-width="120">
        <template #default="scope">
          {{
            scope.row.type === "FIXED"
              ? "固定班次"
              : scope.row.type === "NONE"
              ? "自由工作制"
              : "排班制"
          }}
        </template>
      </el-table-column>

      <el-table-column label="人员" min-width="120">
        <template #default="scope">
          {{ scope.row.user_id.length }}
        </template>
      </el-table-column>

      <el-table-column label="操作" width="150" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)"> 编辑 </el-button>
          <el-button type="danger" link @click="handleDelete(row)"> 删除 </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 新增/编辑抽屉 -->
    <el-drawer
      v-model="drawerVisible"
      v-if="drawerVisible"
      :title="isEdit ? '编辑门店组' : '新增门店组'"
      size="500px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      direction="rtl"
      class="vacation-drawer"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="120px"
        class="drawer-form"
      >
        <el-form-item label="门店组名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入" />
        </el-form-item>

        <div class="form-section">
          <div class="section-title">
            <span>门店人员</span>
            <span style="margin-left: 10px; color: #1890ff" @click="shezhihuixian"
              >设置</span
            >
          </div>

          <div class="section-content">
            <div>
              
              <el-scrollbar height="200px">
                <span>参与门店人员：</span>
               <span>{{ tostringrenyuanName || "未设置" }}</span>
              </el-scrollbar>
             
            </div>
          </div>

          <el-drawer v-model="innerDrawer" title="门店人员" :append-to-body="true">
            <p style="margin: 20px 0">参与门店人员</p>
            <el-select
              placeholder="请选择"
              size="large"
              @click="renyuatianjai"
              style="width: 240px"
            >
            </el-select>

            <div class="renyuan" v-if="renyuanxianshi && MyselectedEmployees.length">
              {{ tostringrenyuanName }}
            </div>

            <template #footer>
              <div style="flex: auto">
                <el-button type="primary" @click="innerDrawer = false">保存</el-button>
              </div>
            </template>
          </el-drawer>
          <p
            v-if="existflack && existname.length > 0"
            style="font-size: 13px; color: #ffc664; margin-top: 3px"
          >
            当前门店组当中{{ existname }}存在于其他门店组当中!
          </p>
        </div>
        <div class="form-section">
          <div class="section-title">
            <span>门店类型</span>
            <span style="margin-left: 10px; color: #1890ff" @click="timeDrawer = true"
              >设置</span
            >
          </div>
          <el-drawer v-model="timeDrawer" title="门店时间" :append-to-body="true">
            <p style="margin: 20px 0">门店类型</p>
            <el-select
              v-model="formData.type"
              placeholder="请选择"
              size="large"
              style="width: 240px"
            >
              <el-option
                v-for="item in timeType"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <p v-if="formData.type == 'FIXED'" style="margin: 20px 0">门店班次</p>
            <el-select
              v-if="formData.type == 'FIXED'"
              v-model="formData.shift_id"
              placeholder="请选择班次"
              size="large"
              style="width: 240px"
              @change="handleChange"
            >
              <el-option
                v-for="item in shiftData"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>

            <template #footer>
              <div style="flex: auto">
                <el-button type="primary" @click="timeDrawer = false">保存</el-button>
              </div>
            </template>
          </el-drawer>
          <div class="section-content">
            <div>
              <span>门店类型：</span>
              <span>
                {{
                  formData.type
                    ? formData.type == "FIXED"
                      ? "固定班次"
                      : formData.type == "NONE"
                      ? "自由工作制"
                      : "排班次"
                    : "未设置"
                }}</span
              >
            </div>
            <div>
              <span>工作日设置：</span>
              <span v-if="formData.type == 'NONE'">自由排班制度</span>
              <span v-else-if="shiftshuzu.length != '0'">
                {{ shiftshuzu }}
              </span>
              <span v-else="shiftshuzu.length == '0'"> 未设置 </span>
            </div>
          </div>
        </div>

        <div class="form-section">
          <div class="section-title">
            <span>打卡方式</span>
            <span @click="dakaDrawer = true" style="margin-left: 10px; color: #1890ff"
              >设置</span
            >
          </div>
          <div class="section-content">
            <div>
              <span>门店方式：</span>
              <span>地点打卡</span>
            </div>
            <el-drawer v-model="dakaDrawer" title="门店打卡" :append-to-body="true">
              <p style="margin: 20px 0">门店班次：地点打卡</p>
              <span>地点：</span>
              <el-button v-if="!locationmassge" @click="areaVisible = true"
                >添加</el-button
              >
              <el-button v-if="locationmassge" @click="areaVisible = true"
                >修改</el-button
              >
              <div v-if="!areaVisible">
                <span> {{ locationmassge }} </span>
              </div>

              <template #footer>
                <div style="flex: auto">
                  <el-button type="primary" @click="dakaDrawer = false">保存</el-button>
                </div>
              </template>
            </el-drawer>
          </div>
        </div>
      </el-form>

      <template #footer>
        <div class="drawer-footer">
          <el-button @click="canslevalue">取消</el-button>
          <el-button type="primary" @click="handleSubmit">保存</el-button>
        </div>
      </template>
    </el-drawer>
    <!--    部门和人员选择对话框-->
    <el-dialog
      v-model="departmentDialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      title="选择部门与人员"
      center
      width="900"
    >
      <div class="dialog">
        <div class="dialog-left">
          <div class="left">
            <el-input
              v-model="queryParams.keyword"
              style="margin-bottom: 10px"
              type="text"
              prefix-icon="el-icon-search"
              size="small"
              placeholder="输入员工姓名全员搜索"
            />
            <!-- 树形组件 -->
            <el-table
              v-loading="departmentStore.loading"
              :data="departmentStore.departmentList"
              element-loading-text="加载中..."
              row-key="selfid"
              border
              default-expand-all
              :tree-props="{ children: 'childs', hasChildren: 'hasChildren' }"
              style="height: 100%; overflow: hidden"
            >
              <OrganizationNameColumn
                v-if="drawerVisible"
                selectable="false"
                hoverable="true"
                @select="selectNode"
                widths="50px"
              />
            </el-table>
          </div>
        </div>
        <div class="dialog-right">
          <el-table
            ref="employeeTable"
            :data="employeeData"
            style="width: 100%"
            @select="handleSelectionChange"
            @select-all="selectAllSelect"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="staffPhoto" align="center" label="头像">
              <template v-slot="{ row }">
                <el-avatar v-if="row.staffPhoto" :src="row.staffPhoto" :size="30" />
                <span v-else class="username">{{ row.username.charAt(0) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="username" label="姓名" />
          </el-table>
        </div>
        <div class="dialog-leftqw">
          <el-table
            :data="selectedEmployees"
            style="width: 100%"
            @cell-click="delleteSelect"
          >
            <el-table-column prop="staffPhoto" align="center" label="头像">
              <template v-slot="{ row }">
                <el-avatar v-if="row.staffPhoto" :src="row.staffPhoto" :size="30" />
                <span v-else class="username">{{ row.username.charAt(0) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="username" label="姓名" />
            <el-table-column label="" width="50">
              <span>×</span>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div class="button-content">
        <el-button @click="qurenvaluerenyuan">取消</el-button>
        <el-button type="primary" @click="qurenvaluerenyuan">确定</el-button>
      </div>
    </el-dialog>
    <!--    打卡对话框-->
    <el-dialog
      v-model="areaVisible"
      v-if="areaVisible"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      title="签到位置"
      width="800"
      style="padding-bottom: 30px"
    >
      <MapContainer v-if="areaVisible" @clickChild="handleLocationSelected" />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from "vue";
import type { FormInstance } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
// import { useVacationStore } from "@/stores/vacation";
import type { VacationRule } from "@/api/types/vacation";
import { getDepartmentList } from "@/api/department";
import { getShiftInfo } from "@/api/shift";
import {
  delAttendanceGroupInfo,
  addAttendanceGroupInfo,
  updateAttendanceGroupInfo,
  getAttendanceGroupInfo,
  exciteddanceGroupInfo,
} from "@/api/attendanceGroup";
import { getUserInfo } from "@/api/employee";
// import AMapLoader from "@amap/amap-jsapi-loader";
import { useDepartmentStore } from "@/stores/department";

const departmentStore = useDepartmentStore();

// 门店人员二级菜单回显
const shezhihuixian = () => {
  innerDrawer.value = true;
  renyuanxianshi.value = true;
};

// 抽屉相关
const areaVisible = ref(false);
const employeeTable = ref(null); // 为 el-table 绑定 ref
const drawerVisible = ref(false);
const isEdit = ref(false);
const loading = ref(true);

// 门店人员回显
const tostringrenyuan = ref(<String>"");
const tostringrenyuanName = ref(<String>"");

// 位置信息
const locationmassge = ref(<String>"");

//存储所有选中的员工
const selectedEmployees = ref(<Array<unknown> | any>[]);

// 初始化列表数据
const dataList = ref(<Array<unknown> | any>[]);

// 我本人选中的员工信息 ID
const MyselectedEmployees = ref(<Array<unknown> | any>[]);

// 部门信息
const userData = ref(<Array<unknown> | any>[]);

// 班次信息
const shiftData = ref(<Array<unknown> | any>[]);

// 门店人员左边显示
const innerDrawer = ref(<boolean>false);

// 部门人员显示按钮用来选人的
const departmentDialog = ref(<boolean>false);

// 打卡地点显示一级框
const dakaDrawer = ref(<boolean>false);
// 门店时间一级显示框
const timeDrawer = ref(<boolean>false);

// 门店添加一级弹框
const formRef = ref<FormInstance>();

//左边显示员工数据
const employeeData = ref(<Array<unknown> | any>[]);

// 门店类型选中信息
const timeType = ref(<Array<unknown> | any>[
  {
    value: "FIXED",
    label: "固定班制（固定时间上下班）",
  },
  // {
  //   value: "TURN",
  //   label: "排班制（按排版上下班）",
  // },
  {
    value: "NONE",
    label: "自由工作制（自由上下班）",
  },
]);

// 门店班次的显示
const shiftDatavalue = ref(<string>"");
const shiftshuzu = ref(<Array<unknown> | any>[]);

// 提交信息
const formData:{
  name?:string,
  type?:string;
 shift_id?:any;
user_id?:[];
address?:string;
 latitude?:string;
longitude?:string;
} = reactive({
  name: "",
  type: "",
  shift_id: "",
  user_id: [],
  workday_class_list: [1, 2, 3, 4, 5, 6, 0],
  address: "",
  latitude: "",
  longitude: "",
  // shop_id: "",
});

// 存储查询参数，记录节点
const queryParams = reactive({
  id: 0,
  page: 1, //当前页
  pagesize: 10,
  keyword: "",
});

// 表单校验规则
const rules = {
  name: [{ required: true, message: "请输入门店组名称", trigger: "blur" }],
  type: [{ required: true, message: "请选择门店类型", trigger: "change" }],
  user_id: [
    {
      type: "array",
      required: true,
      message: "请选择至少一名参与门店人员",
      trigger: "change",
    },
  ],
  shift_id: [{ required: true, message: "请选择门店班次", trigger: "change" }],
};

// 班次选择回显方法
const handleChange = (val: any) => {
  formData.shift_id = val;

  if (formData.shift_id instanceof Array) {
    shiftshuzu.value = [];
    shiftData._rawValue.forEach((item: any) => {
      if (formData.shift_id.includes(item.value)) {
        const aa = item.label.toString();
        const bb = aa.split(" ");
        shiftDatavalue.value = shiftDatavalue.value + "," + bb[0];
        shiftshuzu.value.push(bb[0]);
      }
    });
  } else {
    shiftshuzu.value = [];
    shiftData._rawValue.forEach((item: any) => {
      if (formData.shift_id == item.value) {
        const aa = item.label.toString();
        const bb = aa.split(" ");
        shiftshuzu.value = bb[0];
      }
    });

    // const as=[]
    // as.push(val)
    //  shiftshuzu.value=as
  }
};

// 新增
const handleAdd = () => {
  existname.value = [];
  locationmassge.value = "";
  shiftDatavalue.value = "";
  shiftshuzu.value = [];
  MyselectedEmployees.value = [];
  selectedEmployees.value = [];
  tostringrenyuan.value = "";
  tostringrenyuanName.value = "";
  isEdit.value = false;
  leixing.value = true;
  // if (!isEdit.value) {
  //   leixing.value=true
  // }

  Object.assign(formData, {
    name: "",
    type: "",
    shift_id: "",
    user_id: [],
    workday_class_list: [0, 1, 2, 3, 4, 5, 6],
    address: "",
    latitude: "",
    longitude: "",
  });
  drawerVisible.value = true;
};
//切换节点
const selectNode = async (node: object) => {
  queryParams.id = node.selfid; //重新记录参数
  queryParams.page = 1; //设置第一页
  getUserData();
};
//获取员工表格数据
const getUserData = async () => {
  const res = await getUserInfo(queryParams.id);
  employeeData.value = [];
  res.data.forEach((item: any) => {
    if (item.userid != null && item.userid != " ") {
      employeeData.value.push(item);
    }
  });

  // 将去重后的新数据添加到 employeeData 中
  //  = res.data;
  nextTick(() => {
    toggleSelection(employeeData.value);
  });
};

const renyuanxianshi = ref(false);
// 确认人员的选中
const qurenvaluerenyuan = () => {
  renyuanxianshi.value = true;
  departmentDialog.value = false;
  let aa: any[] = [];
  let aaName: any[] = [];
  selectedEmployees.value.forEach((item: any) => {
    aa.push(item.userid);
    aaName.push(item.username);
  });
  tostringrenyuan.value = aa.join("，");
  tostringrenyuanName.value = aaName.join("，");

  selectedEmployees.value.forEach((item: any) => {
    formData.user_id.push(item.userid);
  });
};

const renyuatianjai = () => {
  renyuanxianshi.value = false;
  departmentDialog.value = true;
};

// 联合下面方法判断选中状态
const flackxuanzhong = ref(true);
//人员表格选择监听
const handleSelectionChange = (selection: any, row: any) => {
  if (MyselectedEmployees.value.includes(row.userid)) {
    selectedEmployees.value = selectedEmployees.value.filter((item: any) => {
      if (item.userid == row.userid) {
        return;
      }
      return item;
    });
    const keixz = MyselectedEmployees.value.indexOf(row.userid);
    MyselectedEmployees.value.splice(keixz, 1);
  } else {
    MyselectedEmployees.value.push(row.userid);
    selectedEmployees.value.push(row);
  }
};

const selectAllSelect = (selection: any[]) => {
  if (selection.length > 0) {
    selection.forEach((element) => {
      if (MyselectedEmployees.value.indexOf(element.userid) == "-1") {
        selectedEmployees.value.push(element);
        MyselectedEmployees.value.push(element.userid);
      }
    });
  } else {
    selectedEmployees.value = [];
    MyselectedEmployees.value = [];
  }
};

// 显示选中的值打勾
const toggleSelection = (rows: any) => {
  try {
      if (rows) {
    rows.forEach((row: any) => {
      if (MyselectedEmployees.value.includes(row.userid)) {
        employeeTable.value!.toggleRowSelection(row, true); // 默认勾选
      } else {
        employeeTable.value!.toggleRowSelection(row, false); // 不选中
      }
    });
  } else {
    employeeTable.value!.clearSelection();
  }
  } catch (error) {
    
  }

};

// 删除选中内容
const delleteSelect = (row: any) => {
  selectedEmployees.value = selectedEmployees.value.filter((item) => {
    return item.userid != row.userid;
  });

  MyselectedEmployees.value = MyselectedEmployees.value.filter((items) => {
    if (items != row.userid) {
      return items;
    }
  });

  formData.user_id = MyselectedEmployees.value;

  getUserData();
};

// 限制考勤组类型不容许修改
const leixing = ref(<boolean>true);

// 编辑
const handleEdit = async (row: VacationRule) => {
  // 清楚输入框信息
  handleAdd();

  const convertedRows = {
    address: row.address,
    id: row.id,
    latitude: row.latitude,
    longitude: row.longitude,
    name: row.name,
    type: row.type,
    workday_class_list: row.workday_class_list,
    // user_id: MyselectedEmployees.value,
  };
 Object.assign(formData, convertedRows);

  leixing.value = false;

  // 变量填写信息实现信息回显
  locationmassge.value = row.address;

  formData.address = locationmassge.value;

  const bumenid = ref(<Array<unknown> | any>[]);

  const cunzaideyonghu = ref(<Array<unknown> | any>[]);

  // 下面方法使用
  const useridaa: any[] = [];
  const useridaaName: any[] = [];
  row.user_id.forEach((item: { dept_id: any; userid: any; username: any }) => {
    if (bumenid.value.length == 0) {
      bumenid.value.push(item.dept_id);
    } else if (!bumenid.value.includes(item.dept_id)) {
      bumenid.value.push(item.dept_id);
    }
    useridaa.push(item.userid);
    useridaaName.push(item.username);
    MyselectedEmployees.value.push(item.userid);
  });

  tostringrenyuan.value = useridaa.join("，");
  tostringrenyuanName.value = useridaaName.join("，");

  // 获取所有部门人员查询显示
  for (let i = 0; i < bumenid.value.length; i++) {
    const res = await getUserInfo(bumenid.value[i]);
    cunzaideyonghu.value.push(...res.data);
  }

  cunzaideyonghu.value.forEach((item: { userid: string | null }) => {
    if (
      MyselectedEmployees.value.includes(item.userid) &&
      item.userid != " " &&
      item.userid != null
    ) {
      selectedEmployees.value.push(item);
    }
  });

  // 显示边框
  isEdit.value = true;

  const convertedRow = {
    address: row.address,
    id: row.id,
    latitude: row.latitude,
    longitude: row.longitude,
    name: row.name,
    type: row.type,
    workday_class_list: row.workday_class_list,
    user_id: MyselectedEmployees.value,
  };

  if (row.type == "FIXED") {
    shiftshuzu.value.push(row.default_class_id.name);
    formData.shift_id = row.default_class_id.id;
  } else if (row.type == "TURN") {
    formData.shift_id = [];
    row.shift_id.forEach((item: { shiftname: any; shift_id: any }) => {
      shiftshuzu.value.push(item.shiftname);
      formData.shift_id.push(item.shift_id);
    });
  }

  Object.assign(formData, convertedRow);

  await getUserData();
  drawerVisible.value = true;
};

//显示存在人员
const existflack = ref(false);
//存在那个人的名字
const existname = ref([]);

// 删除
const handleDelete = (row: VacationRule) => {
  ElMessageBox.confirm("确定要删除该门店组吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      if (row.id) {
        const res = await delAttendanceGroupInfo(row.id);
        if (res.code == 200) {
          ElMessage.success("删除成功");
          getData();
        } else {
          ElMessage.error("删除失败");
        }
      }
    })
    .catch(() => {});
};

// 保存傍边的取消按钮
const canslevalue = () => {
  handleAdd();
  existflack.value = false;
  tostringrenyuan.value = " ";
  tostringrenyuanName.value = " ";

  drawerVisible.value = false;
};

// 提交表单
const handleSubmit = async () => {
  let uniqueArr1 = Array.from(new Set(MyselectedEmployees.value));
  MyselectedEmployees.value = uniqueArr1;

  let uniqueArr = Array.from(new Set(formData.user_id));
  formData.user_id = uniqueArr;

  formData.address = locationmassge.value;
  const adddate = {
    address: formData.address,
    latitude: formData.latitude,
    longitude: formData.longitude,
    name: formData.name,
    type: formData.type,
    user_id: formData.user_id,
    workday_class_list: formData.workday_class_list,
    enable_camera_check: false,
  };

  try {
    await formRef.value.validate();

    if (formData.user_id.length <= 0) {
      ElMessage.warning("请选择门店人员");
      return;
    }

    if (!formData.type) {
      ElMessage.warning("请选择门店类型");
      return;
    }

    if (formData.type != "NONE") {
      if (formData.shift_id.length == "0") {
        ElMessage.warning("请选择门店班次");
        return;
      }
      if (formData.address == "" || formData.address == null) {
        ElMessage.warning("请选择门店地点");
        return;
      }
    }

    // if (formData.type != "NONE") {

    // }

    if (isEdit.value) {
      if (formData.type == "TURN") {
        adddate.id = formData.id;
        adddate.shift_id = formData.shift_id;
      } else if (formData.type == "FIXED") {
        adddate.id = formData.id;
        adddate.default_class_id = formData.shift_id;
      } else {
        adddate.id = formData.id;
        adddate.freecheck_work_days = [1, 2, 3, 4, 5, 6, 0];

        if (adddate.address == "" || adddate.address == null) {
          delete adddate.address;
          delete adddate.latitude;
          delete adddate.longitude;
        }
      }

      const resexcite = await exciteddanceGroupInfo({
        groupid: formData.id,
        user_id: MyselectedEmployees.value,
      });
      existname.value = [];

      if (resexcite.code == "200") {
        if (resexcite.data.is_exist) {
          selectedEmployees._value.forEach((item: { userid: any; username: any }) => {
            if (resexcite.data.user_id.includes(item.userid)) {
              existname.value.push(item.username);
            }
          });
          existflack.value = true;
          formData.user_id = [];
          return;
        } else {
          existflack.value = false;
          console.log(adddate);
          const res = await updateAttendanceGroupInfo(adddate);
          if (res.code == 200) {
            ElMessage.success("更新成功");
            handleAdd();
            getData();
          } else {
            ElMessage.error("更新失败");
          }
        }
      } else {
        formData.user_id = [];
        ElMessage.error("人员查询失败");
      }
    } else {
      if (formData.type == "TURN") {
        adddate.shift_id = formData.shift_id;
      } else if (formData.type == "FIXED") {
        adddate.default_class_id = formData.shift_id;
      } else {
        adddate.freecheck_work_days = [1, 2, 3, 4, 5, 6, 0];
        if (adddate.address == "" || adddate.address == null) {
          delete adddate.address;
          delete adddate.latitude;
          delete adddate.longitude;
        }
      }

      const resexcite = await exciteddanceGroupInfo({
        groupid: "",
        user_id: MyselectedEmployees.value,
      });
      existname.value = [];

      if (resexcite.code == "200") {
        if (resexcite.data.is_exist) {
          selectedEmployees._value.forEach((item: { userid: any; username: any }) => {
            if (resexcite.data.user_id.includes(item.userid)) {
              existname.value.push(item.username);
            }
          });
          existflack.value = true;
          return;
        } else {
          existflack.value = false;

          console.log(adddate);

          const res = await addAttendanceGroupInfo(adddate);
          if (res.code == 200) {
            ElMessage.success("添加成功");
            getData();
          } else {
            ElMessage.error("添加失败");
          }
        }
      } else {
        ElMessage.error("人员查询失败");
      }
    }
    drawerVisible.value = false;
  } catch (error) {
    console.error("表单验证失败:", error);
  }
};

// 处理地点选择事件
const handleLocationSelected = (location: { lng: any; lat: any; locationval: any }) => {
  areaVisible.value = false;
  formData.longitude = location.lng;
  formData.latitude = location.lat;
  formData.address = location.locationval;
  // const aa = location;
  locationmassge.value = location.locationval;

  // 你可以在这里处理用户选择的地点信息
};

// 初始化数据
onMounted(async () => {
  getData();
  await departmentStore.fetchDepartmentList();
  // await nextTick(); // 确保 DOM 更新完成
});

const getData = async () => {
  const res = await getAttendanceGroupInfo();

  loading.value = false;

  dataList.value = res.data.info_list;

  const department = await getDepartmentList();

  userData.value = department.data.info_list;

  const shift = await getShiftInfo();
  shift.data.forEach((item: any) => {
    const trrshijian: any[] = [];
    if (item.sections.length > 1) {
      item.sections.forEach((vak) => {
        const str = vak.times[0].check_time.toString().split(" ")[1];
        const dateval = `${str.split(":")[0]}:${str.split(":")[1]}`;
        const str1 = vak.times[1].check_time.toString().split(" ")[1];
        const dateval1 = `${str1.split(":")[0]}:${str1.split(":")[1]}`;
        trrshijian.push(`${dateval}-${dateval1}`);
      });
      item.timess = `${trrshijian[0]} & ${trrshijian[1]}`;
    } else {
      const str = item.sections[0].times[0].check_time.toString().split(" ")[1];
      const dateval = `${str.split(":")[0]}:${str.split(":")[1]}`;

      const str1 = item.sections[0].times[1].check_time.toString().split(" ")[1];
      const dateval1 = `${str1.split(":")[0]}:${str1.split(":")[1]}`;

      item.timess = `${dateval}-${dateval1}`;
    }
  });

  shiftData.value = shift.data.map((item: { id: any; name: any; timess: any }) => {
    return {
      value: item.id,
      label: `${item.name} (${item.timess}) `,
    };
  });
};
</script>

<style lang="scss" scoped>
.vacation-rules-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h2 {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
    }
  }

  :deep(.el-button) {
    .el-icon {
      margin-right: 4px;
    }
  }
}

.form-section {
  margin-bottom: 24px;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 4px;

  .section-title {
    font-size: 14px;
    font-weight: 700;
    color: #303133;
    margin-bottom: 16px;
  }

  .section-content {
    font-size: 14px;
    color: gray;
  }

  .section-tip {
    font-size: 12px;
    color: #909399;
    margin: -8px 0 16px 120px;
  }

  :deep(.el-form-item:last-child) {
    margin-bottom: 0;
  }
}

.drawer-form {
  padding: 20px;

  :deep(.el-form-item) {
    margin-bottom: 22px;
  }
}

.drawer-footer {
  position: absolute;
  right: 0;
  bottom: 0;
  left: 0;
  padding: 16px 20px;
  background: #fff;
  border-top: 1px solid #dcdfe6;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

// 修改抽屉自定义样式
.vacation-drawer {
  :deep(.el-drawer__header) {
    margin: 0;
    padding: 16px 20px;
    border-bottom: 1px solid #dcdfe6;

    .el-drawer__title {
      font-size: 16px;
      font-weight: 500;
      color: #303133;
    }

    .el-drawer__close-btn {
      margin-right: -6px;
    }
  }

  :deep(.el-drawer__body) {
    padding: 0;
  }
}

:deep(.el-drawer__body) {
  padding-top: 0 !important;
}

:deep(.el-drawer__header) {
  margin-bottom: 0 !important;
  padding-top: 16px !important;
  padding-bottom: 16px !important;
}

.map-container {
  position: relative;
  width: 100%;
  height: 400px;
  /* 确保地图容器有明确的高度 */
}

.map {
  width: 100%;
  height: 100%;
}

.search-bar {
  position: absolute;
  top: 10px;
  left: 10px;
  z-index: 1;
}

.search-bar input {
  padding: 5px;
  width: 200px;
}

.search-bar button {
  padding: 5px 10px;
  margin-left: 5px;
}

.username {
  display: inline-block;
  width: 30px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  background-color: lightblue;
  border-radius: 50%;
  font-size: 14px;
  color: #909399;
}

.dialog {
  height: 380px;
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
}

.dialog-left {
  height: 350px;
  width: 220px;
  transform: scale(1);
  overflow-y: auto;
  /* 添加垂直滚动条 */
  border: 1px solid #dcdfe6;
  /* 可选：添加边框以区分容器 */
  background-color: #fff;
  /* 可选：设置背景颜色 */
}

.dialog-leftqw,
.dialog-right {
  height: 350px;
  width: 300px;
  overflow-y: auto;
  /* 添加垂直滚动条 */
  border: 1px solid #dcdfe6;
  /* 可选：添加边框以区分容器 */
  background-color: #fff;
  /* 可选：设置背景颜色 */
}

.dialog-leftqw {
  margin-left: 40px;
}

.button-content {
  display: flex;
  flex-direction: row;
  justify-content: right;
}

.renyuan {
  cursor: not-allowed;
  background-color: #f5f7fa;
  margin-top: 8px;
  border: 1px solid #e8e8e8;
  padding-left: 8px;
  padding-right: 8px;
  height: 40px;
  width: 350px;
  line-height: 40px;
  border-radius: 5px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 确保表格内容不会超出容器 */
.el-table {
  height: 100%;
  overflow: hidden;
}

/* 自定义滚动条样式 */
.dialog-left,
.dialog-right {
  scrollbar-width: thin;
  /* Firefox */
  scrollbar-color: #ccc #f1f1f1;
  /* Firefox */
}

.dialog-left::-webkit-scrollbar,
.dialog-right::-webkit-scrollbar {
  width: 8px;
}

.dialog-left::-webkit-scrollbar-thumb,
.dialog-right::-webkit-scrollbar-thumb {
  background-color: #ccc;
  border-radius: 4px;
}

.dialog-left::-webkit-scrollbar-track,
.dialog-right::-webkit-scrollbar-track {
  background-color: #f1f1f1;
}
</style>
